package com.gzx.bi.modular.repayment.client.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.google.common.collect.Lists;
import com.gzx.bi.modular.repayment.client.entity.GzxRepaymentClient;
import com.gzx.bi.modular.repayment.client.mapper.GzxRepaymentClientMapper;
import com.gzx.bi.modular.repayment.client.service.GzxRepaymentClientBatchInsertService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import vip.xiaonuo.common.consts.IntConstant;
import vip.xiaonuo.common.util.CommonDateUtil;
import vip.xiaonuo.common.util.CommonSleepUtil;

import java.util.List;
import java.util.stream.Collectors;

import static org.apache.commons.lang.StringEscapeUtils.escapeSql;

/**
 * @author zjt
 * @description
 * @date 2025/4/9 16:45
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GzxRepaymentClientBatchInsertServiceImpl implements GzxRepaymentClientBatchInsertService {

    private final GzxRepaymentClientMapper repaymentClientMapper;

    /**
     * 批量新增
     *
     * @param repaymentClientList
     */
    @Override
    @DS("bi")
    public void insertBatch(List<GzxRepaymentClient> repaymentClientList) {
        String currDate = CommonDateUtil.getCurrentTimeStr();
        List<List<GzxRepaymentClient>> batchList = Lists.partition(repaymentClientList, IntConstant.VALUE_1000);
        for (List<GzxRepaymentClient> batch : batchList) {
            long batchTime = System.currentTimeMillis();
            String sql = batch.stream()
                    .map(s -> String.format("('%s','%s', '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s')",
                            escapeSql(s.getProjectCode()),
                            escapeSql(s.getDebtorUserNo()),
                            escapeSql(s.getRepaymentDate()),
                            escapeSql(String.valueOf(s.getRepaymentAmount())),
                            escapeSql(s.getOverdueDate()),
                            escapeSql(String.valueOf(s.getOverdueDays())),
                            escapeSql(s.getBatch()),
                            escapeSql(s.getAllJson()),
                            escapeSql(s.getDeptId().toString()),
                            escapeSql(s.getTenantId()),
                            escapeSql(s.getCreateUser()),
                            escapeSql(currDate)))
                    .collect(Collectors.joining(", "));
            repaymentClientMapper.insertBatchByValSql(sql.replace("'null'", "null"));
            log.info("甲方还款数据导入：本批次共计：{}条，耗时：{}", batch.size(), System.currentTimeMillis() - batchTime);
            CommonSleepUtil.sleep(IntConstant.VALUE_300);
        }
    }
}
